package com.lengyu.vxminiprogram.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lengyu.vxminiprogram.common.AuthUtil;
import com.lengyu.vxminiprogram.common.BasePageParamDto;
import com.lengyu.vxminiprogram.common.ConstData;
import com.lengyu.vxminiprogram.common.HttpResultDto;
import com.lengyu.vxminiprogram.convert.IUserConverter;
import com.lengyu.vxminiprogram.dto.UserDto;
import com.lengyu.vxminiprogram.entity.User;
import com.lengyu.vxminiprogram.security.rest.dto.JwtUser;
import com.lengyu.vxminiprogram.service.IUserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Paths;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liuyu
 * @since 2023-01-18
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IUserConverter userConverter;


    @PostMapping(value="/saveVxUser")
    public HttpResultDto<String> saveVxUser(@RequestBody UserDto userDto){

        User user = userConverter.dtoToEntity(userDto);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("vx_open_id",user.getVxOpenId());
        User bakUser = userService.getOne(queryWrapper ,false);
        if(bakUser != null){
//            bakUser.setPassword(DigestUtils.md5Hex(ConstData.PASSWORD_SALT +  "ggdsmedar"));
            bakUser.setVxAvatar(user.getVxAvatar());
            bakUser.setVxNickName(user.getVxNickName());
            bakUser.setUsername(user.getVxNickName());
            userService.saveOrUpdate(bakUser);
            return HttpResultDto.success();
        }
        else{
            return  HttpResultDto.failed("账号信息读取错误，请重试");
        }


    }

    /**
     * 批量导入文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload-file")
    public HttpResultDto<String> uploadFile(@RequestPart("file") MultipartFile file){
        JwtUser currentUser = AuthUtil.getCurrentJwtUser();
        if(currentUser == null){
            return HttpResultDto.failed("无权限");
        }
        //判断文件是否为空
        if(file.isEmpty()){
            return HttpResultDto.failed("文件不能为空");
        }
        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();

            // 获取文件的字节
            byte[] bytes = file.getBytes();

            // 这里可以添加保存文件的代码，例如将文件保存到磁盘或数据库
            // 保存文件到本地的路径
            String savePath = "/lengyu/nginx/html/download/avatar/" + fileName;
            // 保存文件
            file.transferTo(Paths.get(savePath).toFile());
            String avatarUrl = "https://wow.shuzhipeixian.com:12812/download/avatar/"+fileName;
            return HttpResultDto.success(avatarUrl);
        } catch (Exception e) {
            return HttpResultDto.failed(e.getMessage());
        }
    }

//    @PreAuthorize("hasPermission('*', 'user_edit')")
//    @PostMapping(value="/update")
//    public HttpResultDto<String> update(@RequestBody UserWithPermissionViewDto UserWithPermissionViewDto){
//        User user = userPermiToUserConverter.dtoToEntity(UserWithPermissionViewDto);
//        List<String> roleCodeList = UserWithPermissionViewDto.getRoles();
//        QueryWrapper queryWrapper = new QueryWrapper();
//        List<RoleUserRelation> roleUserRelationList = new ArrayList<>();
//        if(roleCodeList != null && roleCodeList.size() > 0){
//            queryWrapper.in("code",roleCodeList);
//            List<Role> roleList = roleService.list(queryWrapper);
//            if(roleList != null && roleList.size() > 0){
//                roleList.forEach(i->{
//                    RoleUserRelation roleUserRelation = new RoleUserRelation();
//                    roleUserRelation.setUserId(user.getId());
//                    roleUserRelation.setRoleId(i.getId());
//                    roleUserRelation.initInsert();
//                    roleUserRelationList.add(roleUserRelation);
//                });
//            }
//        }
//
//        if(StringUtils.isNotBlank(user.getId())){
//            //更新用户信息时候不更新密码
//            user.setPassword(null);
//            userService.updateById(user);
//            queryWrapper = new QueryWrapper();
//            queryWrapper.eq("user_id",user.getId());
//            roleUserRelationService.remove(queryWrapper);
//            roleUserRelationService.saveBatch(roleUserRelationList);
//        }
//        else{
//            return HttpResultDto.failed("用户ID不存在无法更新");
//        }
//
//        return HttpResultDto.success();
//    }
//    @PreAuthorize("hasPermission('*', 'user_edit')")
//    @PostMapping(value="/delete")
//    public HttpResultDto<String> delete(@RequestBody JSONObject json){
//        List<String> userIds = Arrays.asList(json.getString("ids").split(","));
//        UpdateWrapper updateWrapper = new UpdateWrapper();
//        updateWrapper.set("delete_flag",true);
//        updateWrapper.in("id",userIds);
//        userService.update(updateWrapper);
//        return HttpResultDto.success();
//    }
//
    //参数1(/user/page)指明了访问该接口需要的url，参数2®指明了访问该接口需要的权限。
//    @PreAuthorize("hasPermission('*', 'user_read')")
    @PostMapping(value="/page")
    public HttpResultDto<Page<UserDto>> page(@RequestBody BasePageParamDto pageParamDto){
        QueryWrapper queryWrapper = new QueryWrapper();
        if(pageParamDto.getParamMapObj() != null){
            for(String key:pageParamDto.getParamMapObj().keySet()){
                if(StringUtils.isNotBlank(String.valueOf(pageParamDto.getParamMapObj().get(key)))){
                    queryWrapper.like(key,pageParamDto.getParamMapObj().get(key));
                }
            }
        }
        Page<User> entityPage = userService.page(new Page<>(pageParamDto.getPageIndex(), pageParamDto.getPageSize()),queryWrapper);
        Page<UserDto> dtoPage = userConverter.pageEntityToDto(entityPage);
        return HttpResultDto.success(dtoPage);
    }
//
//    @PreAuthorize("hasPermission('*', 'user_read')")
//    @GetMapping(value="/detail")
//    public HttpResultDto<UserDto> detail(String id){
//        User user = userService.getById(id);
//        UserDto userDto = userConverter.entityToDto(user);
//        return HttpResultDto.success(userDto);
//    }
//
//    @GetMapping(value="/user-info")
//    public HttpResultDto<UserWithPermissionViewDto> getUserInfo(){
//        String userId = AuthUtil.getCurrentJwtUser().getId();
//        UserWithPermissionView user = userWithPermissionViewService.getById(userId);
//        UserWithPermissionViewDto dto = userWithPermissionViewConverter.entityToDto(user);
//        return HttpResultDto.success(dto);
//    }
//
    @PostMapping(value="/list")
    public HttpResultDto<List<UserDto>> list(@RequestBody UserDto user){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.like("vx_nick_name",user.getVxNickName());
        queryWrapper.select("id","vx_open_id","vx_nick_name");
        List<User> entityList = userService.list(queryWrapper);
        List<UserDto> entityDtoList = userConverter.listEntityToDto(entityList);
        return HttpResultDto.success(entityDtoList);
    }
}
